package com.soeasydo.chapt01;

public class ArrayDemo {

    private int[] array;
    private int size;

    public ArrayDemo(int capacity) {
        this.array = new int[capacity];
        this.size = 0;
    }

    public void insert(int element, int index) throws Exception {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("超出数组实际元素范围!");
        }
        if (size >= array.length) {
            resize();
        }
        for (int i = size - 1; i >= index; i--) {
            array[i + 1] = array[i];
        }
        array[index] = element;
        size++;
    }

    private void resize() {
        int[] arrayNew = new int[array.length * 2];
        System.arraycopy(array, 0, arrayNew, 0, array.length);
        array = arrayNew;
    }

    public void output() {
        for (int i = 0; i < size; i++) {
            System.out.println(array[i]);
        }
        System.out.println("length:--"+array.length);
    }

    public static void main(String[] args) throws Exception {
        ArrayDemo arrayDemo = new ArrayDemo(2);
        arrayDemo.insert(12, 0);
        arrayDemo.insert(11, 0);
        arrayDemo.insert(10, 0);
        arrayDemo.insert(9, 3);
        arrayDemo.insert(9, 3);
        arrayDemo.output();

    }
}
